package com.icloud.common.web.component;

import com.icloud.common.web.util.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;


/**
 *
 * Created by im on 2018/4/26.
 */
@Slf4j
@Component("messageSource")
public class CustomMessageSource extends AbstractMessageSource {

    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        String msg = this.getSourceFromCacheMap(code, locale);
        return new MessageFormat(msg, locale);
    }

    @Override
    protected String resolveCodeWithoutArguments(String code, Locale locale) {
        return this.getSourceFromCacheMap(code, locale);
    }

    /**
     * 从缓存中获取指定国际化资源
     */
    public String getSourceFromCacheMap(String code, Locale locale) {
        //当前语言
        String language = ObjectUtils.isEmpty(locale) ? LocaleContextHolder.getLocale().toString() : locale.toString();
        //内存中的多语言文案
        Map<String, String> localeMsgMap = I18nUtil.getI18nCacheMap(language);
        //获取缓存中对应语言的所有数据项
        if (!ObjectUtils.isEmpty(localeMsgMap) && localeMsgMap.containsKey(code)) {
            //如果对应语言中能匹配到数据项，那么直接返回
            return localeMsgMap.get(code);
        }
        // 如果找不到国际化消息,就直接返回code
        return code;
    }
}
